/**
 * 
 */
package com.hjb.service.impl.Wechat;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hjb.service.Wechat.WechatService;
import com.hjb.service.config.rest.RestClient;
import com.hjb.service.domain.AccessToken;
import com.hjb.service.domain.siteuser.SiteUser;
import com.hjb.service.dto.ActionInfo;
import com.hjb.service.dto.ErweimaTicket;
import com.hjb.service.dto.Scene;
import com.hjb.service.mapper.AccessTokenMapper;
import com.hjb.service.mapper.SiteUserMapper;
import com.hjb.service.utils.FileManage;
import com.hjb.service.utils.StringUtil;
import com.hjb.service.utils.TextMessage;
import com.hjb.service.utils.WechatMessageUtil;
import com.hjb.service.wx.WxConstants;

import tk.mybatis.mapper.entity.Example;

/**
 * 微信公众号交互相关
* @ClassName: ActionInfo
* @author <a href="mailto:125671254@qq.com">Pan Xinwen</a>panxinwen
* @date 2018年1月8日 下午9:28:49
*
*/
@Service
public class WechatServiceImpl implements WechatService {

	private Logger log = LoggerFactory.getLogger(WechatServiceImpl.class);
	@Autowired
	private RestClient restClient;
	@Autowired
	private AccessTokenMapper accessTokenMapper;
	@Autowired
	private SiteUserMapper siteUserMapper;
	
	@Value("${jixing.wx.token}")
	private String jixingWxToken;
	
	@Value("${jixing.wx.user.access.token}")
	private String jixingWxUserAccessToken;
	
	@Value("${jixing.service.base.url}")
	private String jixingServiceBaseUrl;
	
    @Value("${jixing.wx.token.url}")
    private String wxTokenUrl;
    
    @Value("${jixing.wx.ticket.url}")
    private String wxTicketUrl;
	
    @Value("${jixing.wx.snsapi.base}")
    private String wxSnsapiBase;
    
    @Value("${jixing.wx.erweima.ticket}")
    private String wxErweimaTicket;
    
    @Value("${jixing.wx.geterweima}")
    private String jixingWxGeterweima;
    
    @Value("${jixing.erweima.url}")
    private String jixingErweimaUrl;
    
	/* (non-Javadoc)
	 * @see com.shop.service.api.online.WxUtilService#getAccess_token(javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public List<AccessToken> getAccess_token() { 
//		log.info("获取Access_token开始，url========"+wxProperties.getToken_url());
//		String result = restClient.get(wxProperties.getToken_url(), new HashMap<String,Object>(), String.class);  
//		log.info("微信服务器获取Access_token:"+result);
//		JSONObject obj = new JSONObject(result);
//		String access_token = obj.getString("access_token");
//		Map<String,Object> map = new HashMap<String,Object>();
//		map.put("id", 10000);
//		map.put("access_token", access_token);
//		wxUtilMapper.updateByPrimaryKey(map); 
		return accessTokenMapper.selectAll();

	}
	@Override
	public void updateAccess_token() {
		log.info("获取Access_token开始，url========"+wxTokenUrl);
		String result = restClient.get(wxTokenUrl, new HashMap<String,Object>(), String.class);  
		log.info("微信服务器获取Access_token:"+result);
		JSONObject obj = JSONObject.parseObject(result);
		String access_token = obj.getString("access_token");
		String ticket = restClient.get(wxTicketUrl+access_token, new HashMap<String,Object>(), String.class);
		obj = JSON.parseObject(ticket);
		String jsapi_ticket = obj.getString("ticket");
		
		AccessToken wt = new AccessToken();
		wt.setId(Long.parseLong("10000"));
		wt.setAccessToken(access_token);
		wt.setJsapiTicket(jsapi_ticket);
		accessTokenMapper.updateByPrimaryKey(wt);
		
	}
	@Override
	public void snsapibase(String redirect_uri,HttpServletResponse response) {
		String baseUrl = wxSnsapiBase;
		
		try {
			String url = URLEncoder.encode(jixingServiceBaseUrl+"/redirect", "UTF-8");
			baseUrl=baseUrl+"&redirect_uri="+url+"&response_type=code&scope=snsapi_userinfo&state=23#wechat_redirect";
			log.info("用户同意授权，获取code，url========"+baseUrl);
//			String result = restClient.get(baseUrl,new HashMap<>(),String.class);
			try {
				response.sendRedirect(baseUrl);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
//			log.info("用户同意授权返回========"+result);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
	}
	
	@Override
	public String redirect(HttpServletRequest request) {
		
		String code = request.getParameter("code");
		String baseUrl = jixingWxUserAccessToken+"&code="+code+"&grant_type=authorization_code";
		log.info("获取用户access_token，url========"+baseUrl);
		Map<String,Object> map = new HashMap<String,Object>();
		String result = restClient.get(baseUrl,map,String.class);
		log.info("获取用户access_toke返回========"+result);
		return result;
		
	}
	@Override
	public String getErweimaTicket(String phonenumber) {
		log.info("获取二维码：phonenumber==="+phonenumber);
		Scene scene = new Scene();
		scene.setScene_str(phonenumber);
		ActionInfo actionInfo = new ActionInfo();
		actionInfo.setScene(scene);
		
		ErweimaTicket erweimaTicket = new ErweimaTicket();
		erweimaTicket.setAction_info(actionInfo);
		erweimaTicket.setAction_name(WxConstants.QR_LIMIT_STR_SCENE);
		
		AccessToken accessToken = accessTokenMapper.selectByPrimaryKey(10000l);
		String url = wxErweimaTicket+accessToken.getAccessToken();
		
		String result = restClient.post(url, JSONObject.toJSONString(erweimaTicket), String.class);
		
		JSONObject ticketObj = JSON.parseObject(result);
		String ticket = ticketObj.getString(WxConstants.TICKET);
		
		
		try {
			String gEUrl = jixingWxGeterweima+URLEncoder.encode(ticket, "UTF-8");
			FileManage.downLoad(gEUrl, phonenumber+WxConstants.ERWEIMA_TYPE, jixingErweimaUrl);
			log.info("获取二维码成功：phonenumber==="+phonenumber);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return "http://ewm.toohui.com/erweima/"+phonenumber+WxConstants.ERWEIMA_TYPE;
	}
	@Override
	public String wxListener(String signature,  String timestamp,
             String nonce,  String echostr) throws NoSuchAlgorithmException {

		// 将token、timestamp、nonce三个参数进行字典序排序
		String[] params = new String[] {jixingWxToken, timestamp, nonce };
		Arrays.sort(params);
		// 将三个参数字符串拼接成一个字符串进行sha1加密
		String clearText = params[0] + params[1] + params[2];
		String algorithm = "SHA-1";
		String sign = new String(Hex.encodeHex(MessageDigest.getInstance(algorithm).digest((clearText).getBytes()), true));
		// 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
		log.info("signature========" + signature);
		log.info("sign========" + sign);

		if (signature.equals(sign)) {

			log.info("---------------微信校验成功-------------");
			return echostr;
		}

		return "";

	}
	@Override
	public String processRequest(HttpServletRequest request) {
		 Map<String, String> map = WechatMessageUtil.xmlToMap(request);
	        log.info("接收到微信推送消息："+JSON.toJSONString(map));
	        // 发送方帐号（一个OpenID）
	        String fromUserName = map.get("FromUserName");
	        // 开发者微信号
	        String toUserName = map.get("ToUserName");
	        // 消息类型
	        String msgType = map.get("MsgType");
	        // 默认回复一个"success"
	        String responseMessage = "success";
	        
	        String Event = map.get("Event");
	        String EventKey =  map.get("EventKey");
	        //建立用户绑定关系
	        if(!StringUtil.isEmpty(Event) && Event.equals("SCAN") && !StringUtil.isEmpty(EventKey)){
	        	Example example = new Example(SiteUser.class);
	        	example.createCriteria().andEqualTo("mobile", EventKey);
	        	SiteUser siteUser = new SiteUser();
	        	siteUser.setOpenid(fromUserName);
	        	siteUserMapper.updateByExampleSelective(siteUser, example);
	        	//二维码状态置为已扫描
	        	
	        }
	        
	        // 对消息进行处理
	        if (WechatMessageUtil.MESSAGE_TEXT.equals(msgType)) {// 文本消息
	            TextMessage textMessage = new TextMessage();
//	            textMessage.setMsgType(WechatMessageUtil.MESSAGE_TEXT);
//	            textMessage.setToUserName(fromUserName);
//	            textMessage.setFromUserName(toUserName);
//	            textMessage.setCreateTime(System.currentTimeMillis());
//	            textMessage.setContent("我已经受到你发来的消息了");
	            responseMessage = WechatMessageUtil.textMessageToXml(textMessage);
	        }
	        log.info(responseMessage);
	        return responseMessage;
	}
	
}
